# -*- coding:utf-8 -*- #
import pyinotify
from pyinotify import WatchManager, Notifier, ProcessEvent

from probe.conf.configure import ROOT

class Process(ProcessEvent):
    """docstring for Process"""
    def add_clock(self, clock):
        """ clock is a threading.Event"""
        self.clock = clock

    def process(self, event):
        """after any file watched is change, make clock set"""
        if event.pathname.endswith('configure.py'):
            self.clock.set()
            print event

    #def process_IN_CREATE(self, event):
        #"""docstring for process_IN_CREATE"""
        #self.process(event)

    def process_IN_CLOSE(self, event):
        self.process(event)

    #def process_IN_MODIFY(self, event):
        #self.process(event)

    #def process_IN_DELETE(self, event):
        #self.process(event)

    #def process_IN_ACCESS(self, event):
        #self.process(event)

    #def process_IN_MOVED_FROM(self, event):
        #self.process(event)

    #def process_IN_MOVED_TO(self, event):
        #self.process(event)

    def Process_IN_CLOSE_WRIT(self, event):
        self.process(event)


def watch(event):
    import os
    clock = event
    
    pathname = os.path.join(ROOT,'conf')

    mask = (pyinotify.IN_CLOSE_WRITE | pyinotify.IN_CREATE |
            pyinotify.IN_MOVED_FROM | pyinotify.IN_DELETE |
            pyinotify.IN_Q_OVERFLOW | pyinotify.IN_MOVED_TO)

    wm = WatchManager()
    p = Process()
    p.add_clock(clock)

    notifier = Notifier(wm, p)
    #excl = pyinotify.ExcludeFilter('*.swp')
    wm.add_watch(pathname,
            mask, rec=False, auto_add=True)

    while True:
        try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            break
